package com.ruoyi.common.core.config;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

/**
 * Copyright (c) 2024, gitee
 * All rights reserved.
 *
 * @author qiupt@gitee.com
 * @description 通过网关封装request的对象中获取traceId，并放入MDC中
 * @date 2024/10/22 16:17
 **/
@Component
@Slf4j
public class TraceIdFilter extends OncePerRequestFilter {

    public static final String TRACE_ID = "traceId";

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        String traceId = request.getHeader(TRACE_ID);
        if (StringUtils.isNotEmpty(traceId)) {
            MDC.put(TRACE_ID, traceId);
        }
        filterChain.doFilter(request, response);
    }
}
